package scatter.captcha.rest.service.impl;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import scatter.captcha.rest.service.ICaptchaBgImageRandomService;
import scatter.common.rest.tools.ThreadContextTool;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Optional;

/**
 * Created by yangwei
 * Created at 2021/1/15 16:32
 */
@Slf4j
public class DefaultCaptchaBgImageRandomServiceImpl implements ICaptchaBgImageRandomService {
    /**
     * 背景图片存放目录地址，多个以逗号分隔
     * 例：http://xxx.com/image{num}.jpg,/usr/local/image{}.jpg
     */
    @Value("${scatter.captcha.bg-image.path-pattern:}")
    private String bgImagePathPattern;

    @Value("${scatter.captcha.bg-image.size:10}")
    private Integer bgImageSize;

    @Override
    public BufferedImage getBgImageRandomInputStream() throws IOException {

        if (StrUtil.isEmpty(bgImagePathPattern)) {
            ClassPathResource classPathResource = new ClassPathResource(StrUtil.format("bg/img{}.jpg", RandomUtil.randomInt(6)));
            return ImgUtil.read(classPathResource.getInputStream());
        }

        String[] split = bgImagePathPattern.split(",");
        int randomPathNum = RandomUtil.randomInt(split.length);
        String path = split[randomPathNum];
        return getRandomImage(path, bgImageSize,10);
    }

    /**
     * 随机获取背景图片
     * @param pathPattern
     * @param bgImageSize
     * @param tryTotalNum
     * @return
     */
    BufferedImage getRandomImage(String pathPattern, Integer bgImageSize,int tryTotalNum) {
        if(tryTotalNum < 0 || bgImageSize < 0) {
            return null;
        };
        int randomNum = RandomUtil.randomInt(bgImageSize);
        String realPath = StrUtil.format(pathPattern, randomNum);
        BufferedImage read = null;
        try {
            if (pathPattern.startsWith("http")) {
                read = ImageIO.read(new URL(realPath));
                return read;
            }
            read = ImageIO.read(new File(realPath));
        } catch (IOException e) {
            Integer tryNum = (Integer) ThreadContextTool.get("DefaultCaptchaBgImageRandomServiceImpl");
            int realTryNum = Optional.ofNullable(tryNum).map(item-> item + 1).orElse(1);
            ThreadContextTool.put("DefaultCaptchaBgImageRandomServiceImpl",realTryNum);
            log.info("获取背景图片不存在 path={},重试第{}次",realPath,realTryNum);
            return getRandomImage(pathPattern, randomNum, tryTotalNum - 1);
        }
        return read;
    }
}
